<?php

declare(strict_types=1);

namespace app\admin\service\science;

use app\common\model\ScienceReportModel;
use app\common\model\ScienceModel;
use app\common\model\user\UserModel;
use Dengje\Pxy\BaseService;
use think\Request;

class ReportService extends BaseService
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new ScienceReportModel();
    }

    public function list()
    {
        $where = [];
        $order = ['id' => 'desc'];
        $status = request()->get('status', '');
        $article_id = request()->get('article_id', '');
        $user_id = request()->get('user_id', '');
        // 确保$title是字符串类型并去除首尾空白
        $title = (string) request()->get('title', '');
        $title = trim($title);

        if ($status !== '') $where[] = ['status', '=', $status];
        if ($article_id) $where[] = ['article_id', '=', $article_id];
        if ($user_id) $where[] = ['user_id', '=', $user_id];

        // 初始化查询构造器
        $query = $this->model->where($where)->order($order);
            // 没有标题搜索时，正常加载关联
        $query->with(['article', 'user']);
       
        $query->whereExists(function ($query)use($title){
				$query->name('science')->where("title",'like',"%$title%");
			});
        // 执行实际的查询
        $list = $query->paginate(request()->get('page_size/d', 10));

        // 添加状态文本
        $list->map(function ($v) {
            $v['status_text'] = ScienceReportModel::$statusMap[$v['status']] ?? '未知';
            $v['process_time'] = date('Y-m-d H:i:s', $v['process_time']);
            return $v;
        });
        return $list;
    }

    public function detail($id)
    {
        $detail = $this->model->field("*,process_note as process_remark")->where('id', $id)->with(['article', 'user'])->find();
        if ($detail) {
            $detail['status_text'] = ScienceReportModel::$statusMap[$detail['status']] ?? '未知';
            $detail['process_time'] = date('Y-m-d H:i:s', $detail['process_time']);
        }
        return $detail;
    }

    /**
     * 处理投诉
     * @param int $id
     * @param mixed $request
     * @return bool
     */
    public function process(int $id, $request): bool
    {
        $params = $request->param();
        $this->model = new ScienceReportModel();
        $report = $this->model->findOrEmpty($id);
        
        if ($report->isEmpty()) {
            // 如果是新建举报
            $report = new ScienceReportModel();
            $report->article_id = $params['article_id'] ?? 0;
            $report->user_id = $params['user_id'] ?? 0;
            $report->reason = $params['reason'] ?? '';
            $report->create_time = time();
        } else {
            // 更新举报信息
            if (isset($params['reason'])) {
                $report->reason = $params['reason'];
            }
            if($report['status'] != 0){
                throw new \Exception('已处理，不能重复处理');
            }
        }

        // 根据操作类型处理文章
        // if (!empty($params['action_type'])) {
        //     $scienceModel = new ScienceModel();
        //     $article = $scienceModel->find($report->article_id);
        //     if ($article) {
        //         if ($params['action_type'] == 'hide') {
        //             // 隐藏文章
        //             $article->status = 0;
        //             $article->save();
        //         } elseif ($params['action_type'] == 'delete') {
        //             // 删除文章
        //             $article->delete();
        //         }
        //     }
        // }
        
        // 如果设置了状态，调用模型的handleReport方法处理举报
        if (isset($params['status'])) {
            $adminId = (int)cookie('admin_id');

            // 构建处理结果备注
            $handleResult = [];
            if (!empty($params['process_note'])) {
                $handleResult[] = $params['process_note'];
            }
            if (!empty($params['action_type'])) {
                $actionText = $params['action_type'] == 'hide' ? '隐藏文章' : ($params['action_type'] == 'delete' ? '删除文章' : $params['action_type']);
                $handleResult[] = "处理操作：$actionText";
            }
            $res =  $this->model->handleReport($id, $adminId, $params['status'], implode('; ', $handleResult));

            return $res;
        }

        return $report->save();
    }

    public function delete()
    {
        $id = request()->param('id', 0);

        $this->model->where('id', $id)->delete();
        return success('删除成功');
    }
}